//
//  PictureSelectViewController.swift
//  weibo
//
//  Created by apple on 15/12/24.
//  Copyright © 2015年 LYR. All rights reserved.
//
                          
import UIKit

private let reuseIdentifier = "Cell"
private let rowCount: CGFloat = 5
private let margin: CGFloat = 5
private let maxImageCount = 9

class PictureSelectViewController: UICollectionViewController {
    
    // 定义照片数组
    var imageList = [UIImage]()
    
    init() {
    
        //设置layout
        let layout = UICollectionViewFlowLayout()
        // 设置每个cell的宽度
        let itemW = (screenW - rowCount * margin) / rowCount
        layout.itemSize = CGSizeMake(itemW, itemW)
        
        
        super.init(collectionViewLayout: layout)
        
        collectionView?.backgroundColor = UIColor.whiteColor()
    
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()

        // Register cell classes  注册cell
        self.collectionView!.registerClass(PictureSelectCell.self, forCellWithReuseIdentifier: reuseIdentifier)

    }

    // MARK: UICollectionViewDataSource  数据源方法

    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }


    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        
        let delta = imageList.count == maxImageCount ? 0 : 1
    
        return imageList.count + delta
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PictureSelectCell
    
        //设置代理
        cell.delegate = self
        
        //设置数据源
        if indexPath.item == imageList.count {
          cell.image = nil
        } else {
        
          cell.image = imageList[indexPath.item]
        }

        return cell
    }
}

//遵守协议
extension PictureSelectViewController: PictureSelectCellDelegate {

    func userWillDeletePicture(cell: PictureSelectCell) {
      //1.通过获取的cell 找到对应的indexPath
        if let index = collectionView?.indexPathForCell(cell) {
        
            //在数组中 删除对应的indexPaht.item角标下的元素
            imageList.removeAtIndex(index.item)
            
            //操作完数据源  执行刷新
            collectionView?.reloadData()
        }
    }
    
    //用户选择图片
    func userWillChosePicture(cell: PictureSelectCell) {
        //如果点击的cell 的image不为nil 的话就直接返回
        if cell.image != nil {
        
            print("已经有图片")
             return
        }
        
        //选择图片   得到图片选择器
        let picker = UIImagePickerController()
        
        //modal 出对应的图片选择器
        presentViewController(picker, animated: true, completion: nil)
        
        //询问用户访问权限 是iOS7之后  需要经过用户同意之后才能够获取用户个人隐私数据
        // 2.设置图片选择器的代理
        //一旦指定了代理对象 之后 就需要程序员手动dismiss picker
        
        picker.delegate = self
        
    }
}
//MARK:  ??????
extension PictureSelectViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {

    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        //将获取的图片 添加到数组中  修改数组
        imageList.append(image)
        
//        print(imageList.count)
        
        //刷新列表
        collectionView?.reloadData()
        
        //手动dismiss
        dismissViewControllerAnimated(true, completion: nil)
        
    }
}


//MARK:定义自定义cell的协议
@objc protocol PictureSelectCellDelegate: NSObjectProtocol {

   //  协议方法
    //添加图片
    optional func userWillChosePicture(cell: PictureSelectCell)

    //删除图片
    optional func userWillDeletePicture(cell: PictureSelectCell)

}

//MARK:自定义cell
class PictureSelectCell: UICollectionViewCell {
    
    //MARK:定义外部模型属性
    var image: UIImage? {
    
        didSet {
        //  如果设置的图片为空  就隐藏删除按钮
           deleteBtn.hidden = image == nil
           addBtn.setImage(image, forState: .Normal)
        }
    }
    
    //点击添加按钮事件
    @objc private func addBtnClick() {
        //使用代理调用协议方法
        //delegate? 表示 协议是否为空
       delegate?.userWillChosePicture?(self)
    
    }
    
    //点击删除图片按钮
    @objc private func deleteBtnClick() {
        delegate?.userWillDeletePicture?(self)
        
    }
    
    //MARK:  声明一个 弱引用的代理对象
    weak var delegate: PictureSelectCellDelegate?
    
    //MARK:重写构造方法
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //MARK:设置页面 布局
    private func setupUI() {
        
        //设置btn 背景图片的样式
        addBtn.imageView?.contentMode = .ScaleAspectFill
        
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        
        //设置约束
        addBtn.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(contentView.snp_edges)
        }
        
        deleteBtn.snp_makeConstraints { (make) -> Void in
            
            make.top.right.equalTo(addBtn)
        }
        
        //添加按钮事件
        addBtn.addTarget(self, action: "addBtnClick", forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: "deleteBtnClick", forControlEvents: .TouchUpInside)
        
        
    }
    
    // MARK:懒加载所有的子视图
    private lazy var deleteBtn: UIButton = UIButton(imageName: nil, backImageName: "compose_photo_close")
    private lazy var addBtn: UIButton = UIButton(imageName: nil, backImageName: "compose_pic_add")
    
}
